import axios from "axios";
import { Toast } from "vant";
// localStorage.setItem(
//   'fuhuibatoken',
//   'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJiaXphZG1pbiIsIm1ldGhvZCI6MCwiZXAiOiJ3ZWIiLCJ2ZXJzaW9uIjoiMS4wLjAiLCJzaG9wX2lkIjowLCJ1c2VyX2lkIjoiMSIsInNjb3BlIjoiYnVzaW5lc3MiLCJpZCI6IjEiLCJidXNpbmVzc19pZCI6MSwiZXhwIjoxNjQ2OTg2OTEyfQ.vP0v_cNjUvf0mpXfjZG3vCqt90-PiFs8nhVaVKh_vdE'
// )
var url = decodeURI(window.location.href); //获取url中"?"符后的字串
var Urldata = new Object();
if (url.indexOf("?") != -1) {
  let param = url.split("?")[1]; //获取param
  let arr = param.split("&");
  for (let i = 0; i < arr.length; i++) {
    let arr_param = arr[i].split("=");
    Urldata[arr_param[0]] = arr_param[1];
  }
  localStorage.setItem("Urldata", JSON.stringify(Urldata));
}

if (Urldata.token) {
  localStorage.setItem("fuhuibatoken", Urldata.token);
}

axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
// 勿动 避免本地调试代码误发布到测试环境
// if (process.env.NODE_ENV == "development") {
//   // axios.defaults.baseURL = '/api'
//   axios.defaults.baseURL = "http://192.168.111.135:8080";
//   // axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
// } else if (process.env.NODE_ENV == "production") {
//   axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
// }

axios.defaults.timeout = 60000;
//192.168.111.146:6300
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8";
// axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';

axios.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("fuhuibatoken");
    if (token) {
      config.headers["Cloud-Auth"] = "bearer " + token;
      config.headers["X-BUSINESS-TOKEN"] = token;
      // let arr = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxNTA1MDEwODA0Nzk2MDk2NTEzIiwibWV0aG9kIjowLCJlcCI6IndlYiIsInZlcnNpb24iOiIxLjAuMCIsInVzZXJfaWQiOiI4ODg4Iiwic2NvcGUiOiJidXNpbmVzcyIsImlkIjoiMTUwNTAxMDgwNDc5NjA5NjUxMyIsImJ1c2luZXNzX2lkIjoxNTA1MDEwODA0Nzk2MDk2NTEzLCJleHAiOjE2NTExNTMzODd9.7uzyV_itMgeL5kcZFKuvEb635VonTrPEjTDW6_ryIgw'
      // config.headers['Cloud-Auth'] = 'bearer ' + arr
      // config.headers['X-BUSINESS-TOKEN'] = arr
    }
    // console.log('config',config)
    return config;
  },
  (error) => {
    return Promise.error(error);
  }
);

axios.interceptors.response.use(
  (response) => {
    if (response.data.code !== 200) {
      // Toast({
      //     message: response.data.message || response.data.msg,
      //     duration: 2000,
      //     forbidClick: true,
      // })
      return Promise.resolve(response);
    }
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    if (error.response.status) {
      switch (error.response.status) {
        case 401:
          Toast({
            message: "登录过期，请重新登录",
            duration: 2000,
            forbidClick: true,
          });
          break;
        case 404:
          Toast({
            message: "网络请求不存在",
            duration: 2000,
            forbidClick: true,
          });
          break;
        default:
          // if (error.response.data.msg == 'OCR recognition failed,OCR识别失败' || error.response.data.msg == 'OCR recognition failed,身份证信息不合法（身份证号、姓名字段校验非法等）'
          // )
          //   return
          var reg = RegExp(/OCR recognition failed/);
          var zeg = RegExp(/OCR识别失败/);
          if (
            error.response.data.msg.match(reg) ||
            error.response.data.msg.match(zeg)
          ) {
            return;
          }
          Toast({
            message: error.response.data.message || error.response.data.msg,
            duration: 2000,
            forbidClick: true,
          });
          break;
      }
      return error.response;
    }
  }
);
export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}
export function post(url, params, headers) {
  return new Promise((resolve, reject) => {
    // axios.post(url, QS.stringify(params))
    axios
      .post(url, params, {
        headers: headers,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}

export function put(url, params, headers) {
  return new Promise((resolve, reject) => {
    // axios.post(url, QS.stringify(params))
    axios
      .put(url, params, {
        headers: headers,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}

export default axios;
